package com.dapeng.cleardatabackend.interceptor;

import com.dapeng.cleardatabackend.common.ErrorCode;
import com.dapeng.cleardatabackend.common.LoginUserHolder;
import com.dapeng.cleardatabackend.exception.BusinessException;
import com.dapeng.cleardatabackend.exception.ThrowUtils;
import com.dapeng.cleardatabackend.model.entity.User;
import com.dapeng.cleardatabackend.model.enums.UserRoleEnum;
import com.dapeng.cleardatabackend.model.enums.UserStatusEnum;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.dapeng.cleardatabackend.contant.UserConstant.USER_LOGIN_STATE;

/**
 * @author dapeng
 */
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) throws Exception {
        // 先判断是否已登录
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null || currentUser.getId() == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        ThrowUtils.throwIf(currentUser.getUserRole() == UserRoleEnum.BAN, ErrorCode.NO_AUTH_ERROR, "用户被封号");
        ThrowUtils.throwIf(currentUser.getUserStatus() == UserStatusEnum.ABNORMAL, ErrorCode.NO_AUTH_ERROR, "用户被禁用");
        LoginUserHolder.setLoginUser(currentUser);
        return true;
    }

    @Override
    public void afterCompletion(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler, Exception ex) throws Exception {
        LoginUserHolder.clear();
    }
}